package jgl.vajra.management.part.home.pop;

import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.management.R;
import jgl.vajra.management.bean.HomeMechanicsBean;
import jgl.vajra.management.databinding.PopAuthenticationScreeningBinding;
import jgl.vajra.management.databinding.PopCustomerRegistrationBinding;
import jgl.vajra.management.event.CustomerOpenCityEvent;
import jgl.vajra.management.event.CustomerRegistrationEvent;
import jgl.vajra.management.event.MyCarListEvent;
import jgl.vajra.management.event.OpenCityEvent;
import jgl.vajra.management.manager.IntentManager;
import jgl.vajra.management.utils.RandomUtils;
import jgl.vajra.management.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.management.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.management.widget.manager.RxJavaHttpManager;
import jgl.vajra.management.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.management.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.management.widget.utils.ToastUtils;
import jgl.vajra.management.widget.utils.UIUtils;

public class CustomerRegistrationPop implements BaseBindingItemPresenter<HomeMechanicsBean> {

    private FragmentActivity activity;
    private View mPopRootView;
    private PopupWindow menuPop;
    private SingleTypeBindingAdapter adapter;
    private List<HomeMechanicsBean> dataBean;
    private PopCustomerRegistrationBinding mBinding;
    private String cityId = "";
    private String mechanicsType = "";
    private String provinceId = "";

    public CustomerRegistrationPop(FragmentActivity activity) {

        this.activity = activity;
    }


    private void initPopupWindow() {
        EventBus.getDefault().register(this);

        mPopRootView = View.inflate(UIUtils.getContext(), R.layout.pop_customer_registration, null);
        mBinding = DataBindingUtil.bind(mPopRootView);

        menuPop = new PopupWindow(mPopRootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        menuPop.setOutsideTouchable(false);
        menuPop.setBackgroundDrawable(new BitmapDrawable());
        menuPop.setFocusable(true);// 点击空白处时，隐藏掉pop窗口
        menuPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //popupwindow消失的时候恢复成原来的透明度
                backgroundAlpha(1f);
            }
        });
        mBinding.setView(this);

        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));//随机数


        //机械类型
        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));
        adapter = new SingleTypeBindingAdapter(activity, null, R.layout.item_all_machinery);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemPresenter(this);

        RetrofitJsonManager.getInstance().getApiService().getCarTypeData(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<List<HomeMechanicsBean>>(false, null) {
                    @Override
                    public void _onNext(List<HomeMechanicsBean> homeMechanicsBean) {
                        HomeMechanicsBean bean = new HomeMechanicsBean();
                        bean.remark = "全部";
                        bean.type = "";
                        bean.isClick = true;
                        homeMechanicsBean.add(0, bean);
                        dataBean = homeMechanicsBean;
                        adapter.refresh(homeMechanicsBean);
                    }

                    @Override
                    public void _onError(String errorMessage, int errorCode) {
                        super._onError(errorMessage, errorCode);
                    }
                });
    }

    public void showPopupWindow(View v) {
        if (menuPop == null)
            initPopupWindow();
        int[] location = new int[2];
        v.getLocationOnScreen(location);  //获取控件的位置坐标
        //获取自身的长宽高
        mPopRootView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        backgroundAlpha(0.5f);

//        menuPop.showAtLocation(v, Gravity.NO_GRAVITY, (int) (location[0] - DisplayUtils.getDimension(R.dimen.dp_4)), (int) (location[1] - mPopRootView.getMeasuredHeight() - DisplayUtils.getDimension(R.dimen.dp_4)));  //显示指定控件的上方
        menuPop.showAsDropDown(v, 0, 0);    //显示指定控件的下方
    }

    public boolean isShowing() {
        return menuPop != null && menuPop.isShowing();
    }

    public void dismiss() {
        EventBus.getDefault().unregister(this);
        if (menuPop != null && menuPop.isShowing())
            menuPop.dismiss();
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        if (activity == null) return;
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);

    }

    @Override
    public void onItemClick(int position, HomeMechanicsBean itemData) {
        if (itemData.isClick) return;
        for (int i = 0; i < dataBean.size(); i++) {
            dataBean.get(i).isClick = false;
        }
        dataBean.get(position).isClick = true;
        adapter.refresh();
        if (!TextUtils.isEmpty(itemData.type)) {
            mechanicsType = itemData.type;
        } else {
            mechanicsType = "";
        }
    }

    public void onOpenCity() {
        IntentManager.toCustomerReceivingAreaActivity(activity);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomerOpenCityEvent(CustomerOpenCityEvent event) {
        cityId = event.cityId;
        if (event.cityId.equals("0")) {
            cityId = "";
        }

        provinceId = event.provinceId;
        mBinding.tvText.setText(event.name);
    }

    //重置
    public void onReset() {
        EventBus.getDefault().post(new CustomerRegistrationEvent("", "", ""));
        dismiss();
    }

    //完成
    public void onDetermine() {
        EventBus.getDefault().post(new CustomerRegistrationEvent(mechanicsType, provinceId, cityId));
        dismiss();
    }
}
